
<template>
  <Dialog v-model="dialogVisible" title="数据导入" width="500">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="所属银行" prop="deptId">
        <el-tree-select
          v-model="formData.deptId"
          :data="deptList"
          :props="defaultProps"
          check-strictly
          node-key="id"
          placeholder="请选择归属银行"
        />
      </el-form-item>

      <el-form-item label="年份" prop="year">
        <el-date-picker
          v-model="formData.year"
          type="year"
          value-format="YYYY"
          placeholder="请选择年份"
        />
      </el-form-item>

      <el-form-item label="季度" prop="quarter">
        <el-select v-model="formData.quarter" placeholder="请选择季度">
          <el-option
            v-for="dict in getIntDictOptions('circ_quarter')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="上报时间" prop="statsDate">
        <el-date-picker
          v-model="formData.statsDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择上报时间"          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="更新数据">
        <el-checkbox v-model="updateSupport" />
        是否更新已经存在的数据
      </el-form-item>

      <el-form-item label="上传文件" prop="file">
        <el-upload
          ref="uploadRef"
          v-model:file-list="fileList"
          :action="importUrl"
          :auto-upload="false"
          :disabled="formLoading"
          :headers="uploadHeaders"
          :limit="1"
          :on-error="submitFormError"
          :on-exceed="handleExceed"
          :on-success="submitFormSuccess"
          :data="formData"
          accept=".xlsx, .xls"
          drag
        >
          <Icon icon="ep:upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip text-center">
              <span>仅允许导入 xls、xlsx 格式文件。</span>
              <el-link
                :underline="false"                style="font-size: 12px; vertical-align: baseline"
                type="primary"
                @click="importTemplate"
              >
                下载模板
              </el-link>
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>import * as UserApi from '@/api/system/user'
import { getAccessToken, getTenantId } from '@/utils/auth'
import download from '@/utils/download'
import type { FormInstance, FormRules } from 'element-plus'
import {getIntDictOptions} from "@/utils/dict";
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import {DataStatsApi} from "@/api/circ/datastats";

defineOptions({ name: 'DataStatsImportForm' })

const message = useMessage() // 消息弹窗
const formRef = ref<FormInstance>() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/circ/data-stats/import'
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表
const updateSupport = ref(false) // 是否更新已经存在的用户数据

// 表单数据
const formData = ref({
  deptId: null,
  year: undefined,
  quarter: undefined,
  statsDate: null
})

// 表单验证规则
const formRules = reactive<FormRules>({
  deptId: [{ required: true, message: '所属银行不能为空', trigger: 'blur' }],
  year: [{ required: true, message: '年份不能为空', trigger: 'change' }],
  quarter: [{ required: true, message: '季度不能为空', trigger: 'change' }],
  statsDate: [{ required: true, message: '上报时间不能为空', trigger: 'change' }]
})


/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  resetForm()
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  const valid = await formRef.value?.validate()
  if (!valid) return

  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }

  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  formLoading.value = true

  // 设置上传参数
  uploadRef.value!.data = {
    updateSupport: updateSupport.value,
    deptId: formData.value.deptId,
    year: formData.value.year,
    quarter: formData.value.quarter,
    statsDate: formData.value.statsDate
  }

  uploadRef.value!.submit()
}

/** 文件上传成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
  // 拼接提示语
  const data = response.data
  let text = '上传成功数量：' + data.createAreaNames.length + ';'
  for (let username of data.createAreaNames) {
    text += '< ' + username + ' >'
  }
  text += '更新成功数量：' + data.updateAreaNames.length + ';'
  for (const username of data.updateAreaNames) {
    text += '< ' + username + ' >'
  }
  text += '更新失败数量：' + Object.keys(data.failureAreaNames).length + ';'
  for (const username in data.failureAreaNames) {
    text += '< ' + username + ': ' + data.failureAreaNames[username] + ' >'
  }
  message.alert(text)
  formLoading.value = false
  dialogVisible.value = false
  // 发送操作成功的事件
  emits('success')
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = async (): Promise<void> => {
  // 重置表单数据
  formData.value = {
    deptId: null,
    year: undefined,
    quarter: undefined,
    statsDate: null
  }
  updateSupport.value = false
  fileList.value = []

  // 重置上传状态和文件
  formLoading.value = false
  formRef.value?.resetFields()
  await nextTick()
  uploadRef.value?.clearFiles()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}

/** 下载模板操作 */
const importTemplate = async () => {
  const res = await DataStatsApi.importDataStatsTemplate()
  download.excel(res, '数据导入模版.xls')
}
</script>
